package com.jzr.medical.controller.api;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jzr.common.BaseController;
import com.jzr.common.entity.vo.Result;
import com.jzr.common.util.MD5Util;
import com.jzr.common.util.U;
import com.jzr.medical.common.LayBatch;
import com.jzr.medical.common.SecurityHelper;
import com.jzr.medical.db1.model.TUser;
import com.jzr.medical.db1.service.UserService;
import com.jzr.medical.db1.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "User接口")
@RestController
@RequestMapping(value = "/api/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @PostMapping("/refesh")
    @ApiOperation("refesh -> 刷新token")
    public Result<String> refeshToken() throws IOException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return Result.success("Refesh成功","1");
    }

    @PostMapping("/logout")
    @ApiOperation("logout -> 注销")
    public Result<Boolean> logout(HttpServletRequest req) throws IOException {
        HttpSession session = req.getSession(false);
        if(session != null){
            session.invalidate();
        }
        return Result.success("Logout成功",true);
    }

    @GetMapping("/getUserInfo")
    @ApiOperation("getUserInfo -> 获取用户信息")
    public Result<UserInfoResult> getUserInfo() throws IOException {
        Integer userId = SecurityHelper.getUserId();
        UserInfoVo userInfoVo = userService.getUserInfoVoById(userId);

        UserInfoResult userInfoResult = new UserInfoResult();
        userInfoResult.setUserInfo(userInfoVo);
        userInfoResult.setRoles(userService.getRoleCodesById(userId));

        return Result.success("getUserInfo成功",userInfoResult);
    }

    @GetMapping("/getMenuList")
    @ApiOperation("getMenuList -> 获取菜单列表")
    public Result<List<UserMenuVo>> getMenuList() throws IOException {
        Integer userId = SecurityHelper.getUserId();
        List<UserMenuVo> list = userService.getMenuByUserId(userId);
        return Result.success("成功",list);
    }
    @GetMapping("/checkLogin")
    @ApiOperation("checkLogin -> 检查是否登录了")
    public Result<Integer> checkLogin(){
        Integer id = SecurityHelper.getUserId();
        if(id == null){
            return Result.fail("没有成功登陆");
        }
        return Result.success("成功",id);
    }

    @RequestMapping("/list")
    public Result<List<UserVo>> list(UserVo record){
        QueryWrapper<UserVo> qw = new QueryWrapper<>();
        qw.likeRight(U.isNotBlank(record.getUserCode()),UserVo.UserCode_,record.getUserCode())
                .likeRight(U.isNotBlank(record.getUserName()),UserVo.UserName_,record.getUserName())
                .likeRight(U.isNotBlank(record.getPhone()),UserVo.Phone_,record.getPhone());
        List<UserVo> list = userService.list(qw);
        return Result.success("成功",list);
    }

    @PostMapping("/add")
    public Result<UserVo> add(UserVo record){
        record.setStatus(1);
        record.setPassword("123456");
        UserVo rt = userService.saveAndGet(record);
        return Result.success("成功",rt);
    }

    @PostMapping("/update")
    public Result<UserVo> update(UserVo record){
        UserVo rt = userService.updateAndGet(record);
        return Result.success("成功",rt);
    }
    @PostMapping("/save")
    public Result<UserVo> save(UserVo record){
        if(!U.isBlank(record.getId())){
            return this.update(record);
        }else{
            Result result = verifyData(record);
            if(result != null){
                return result;
            }
            return this.add(record);
        }
    }
    @PostMapping("/reset")
    public Result<Boolean> reset(Integer id){
        TUser tUser = new TUser();
        tUser.setId(id);
        tUser.setPassword(MD5Util.MD5("123456"));
        userService.updateById(tUser);
        return Result.success("成功",true);
    }

    @PostMapping("/saveBatch")
    public Result<List<UserVo>> saveBatch(@RequestBody List<UserVo> list){
        LayBatch<UserVo> batch = new LayBatch<>(list);
        if(!U.isBlank(batch.getAdds())){
            for(TUser record: batch.getAdds()) {
                Result result = verifyData(record);
                if(record != null){
                    return result;
                }
            }
        }
        List<UserVo>  result = userService.saveBatch(batch);
        return Result.success("成功",result);
    }

    @PostMapping("/changePsw")
    public Result<Boolean> changePsw(String oldPsw, String newPsw, String rePsw){
        if(U.isBlank(oldPsw)){
            return Result.fail("原密码不能为空");
        }
        if(U.isBlank(newPsw)){
            return Result.fail("新密码不能为空");
        }
        if(U.isBlank(rePsw)){
            return Result.fail("确认密码不能为空");
        }
        if(!newPsw.equals(rePsw)){
            return Result.fail("两次密码输入不一致");
        }
        Integer userId = SecurityHelper.getUserId();
        String sysPsw = userService.getPswById(userId);
        if(U.isBlank(sysPsw)){
            return Result.fail("无法获取系统密码");
        }
        if(!oldPsw.equals(sysPsw)){
            return Result.fail("原密码不对");
        }

        TUser user = new TUser();
        user.setId(userId);
        user.setPassword(newPsw);

        Integer count = userService.changePsw(userId,oldPsw,newPsw);
        if(count <= 0){
            return Result.fail("修改失败");
        }

        return Result.success("修改成功",true);
    }

    @GetMapping("/getIndexPageData")
    public Result<Map<String,Object>> getIndexPageData(){
        Map<String,Object> result = new HashMap<>();

        Integer userId = SecurityHelper.getUserId();
        String userCode = SecurityHelper.getUserCode();
        UserInfoVo userInfoVo = userService.getUserInfoVoById(userId);

        result.put("userInfo",userInfoVo);
        result.put("menuList",userService.getMenuByUserId(userId));
        result.put("deptCodeList",userService.getDeptList(userId));

        return Result.success("成功",result);

    }
    @GetMapping("/deptList")
    @ApiOperation("用户的部门列表")
    public Result<List<DeptCodeVo>> deptList(){
        Integer userId = SecurityHelper.getUserId();
        List<DeptCodeVo> list = userService.getDeptList(userId);
        return Result.success("成功",list);
    }

    private Result verifyData(TUser record){
        if(U.isBlank(record.getId())) {
            if (U.isBlank(record.getUserCode())) {
                return Result.fail("账号不能为空");
            }
            if (U.isBlank(record.getUserName())) {
                return Result.fail("用户名不能为空");
            }
            Integer existsId = userService.getIdByUserCode(record.getUserCode());
            if (existsId != null) {
                return Result.fail("该用户账号已经存在");
            }
        }
        return null;
    }


}
